"""
通知 CRUD 操作
"""
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from crud.base import CRUDBase
from models.notification import Notification
from schemas.notification import NotificationCreate, NotificationUpdate


class CRUDNotification(CRUDBase[Notification, NotificationCreate, NotificationUpdate]):
    """通知的 CRUD 操作类"""

    async def get_list(
        self,
        db: AsyncSession,
        *,
        page: int = 1,
        per_page: int = 10,
        is_read: bool = None
    ):
        """
        获取通知列表（分页）
        
        Args:
            db: 数据库会话
            page: 页码
            per_page: 每页数量
            is_read: 是否已读（可选）
        
        Returns:
            通知列表
        """
        query = select(self.model).where(self.model.status == 1)
        
        # 如果指定了已读状态
        if is_read is not None:
            query = query.where(self.model.is_read == is_read)
        
        # 按创建时间倒序排序
        query = query.order_by(self.model.created_at.desc())
        
        # 计算偏移量
        offset = (page - 1) * per_page
        
        # 执行分页查询
        query = query.offset(offset).limit(per_page)
        result = await db.execute(query)
        return result.scalars().all()

    async def count_all(
        self,
        db: AsyncSession,
        *,
        is_read: bool = None
    ) -> int:
        """
        统计通知总数
        
        Args:
            db: 数据库会话
            is_read: 是否已读（可选）
        
        Returns:
            通知总数
        """
        query = select(func.count(self.model.id)).where(self.model.status == 1)
        
        if is_read is not None:
            query = query.where(self.model.is_read == is_read)
        
        result = await db.execute(query)
        return result.scalar()

    async def get_all(
        self,
        db: AsyncSession,
        *,
        is_read: bool = None
    ):
        """
        获取所有通知（不分页）
        
        Args:
            db: 数据库会话
            is_read: 是否已读（可选）
        
        Returns:
            所有通知列表
        """
        query = select(self.model).where(self.model.status == 1)
        
        if is_read is not None:
            query = query.where(self.model.is_read == is_read)
        
        # 按创建时间倒序排序
        query = query.order_by(self.model.created_at.desc())
        
        result = await db.execute(query)
        return result.scalars().all()

    async def soft_delete(
        self,
        db: AsyncSession,
        *,
        notification_id: int
    ) -> bool:
        """
        软删除通知
        
        Args:
            db: 数据库会话
            notification_id: 通知ID
        
        Returns:
            是否删除成功
        """
        notification = await self.get(db, id=notification_id)
        if not notification:
            return False
        
        notification.status = 0
        await db.commit()
        return True


# 创建 CRUD 实例
crud_notification = CRUDNotification(Notification)

